require("dotenv").config();
var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
const JWT = require("./utils/JWT");
const cors = require("cors");
const fs = require("fs");
var expressip = require("express-ip");
const userAuth = require("./middleware/userAuth");

// 设置 SERVER_BASE_URL 环境变量
if (process.env.NODE_ENV === 'prod') {
  process.env.SERVER_BASE_URL = 'http://www.hwhanbaodan.top:3000';
} else {
  process.env.SERVER_BASE_URL = process.env.SERVER_BASE_URL || 'http://localhost:3000';
}
// 后台路由导入
const userRouter = require("./routes/admin/userRouter");
const articleRouter = require("./routes/admin/articleRouter");
const sourceRouter = require("./routes/admin/sourceRouter");
const tagsRouter = require("./routes/admin/tagsRouter");
const categoryRouter = require("./routes/admin/categoryRouter");
const guestbookRouter = require("./routes/admin/guestbookRouter");
const imageCategory = require("./routes/admin/imageCategory");
const imageRouter = require("./routes/admin/imageRouter");
const dashboardRouter = require("./routes/admin/dashboardRouter");
const animationRouter = require("./routes/admin/animationRouter");
const trendsRouter = require("./routes/admin/trendsRouter");
// 路由导入

// 前台路由导入
const authHomeRouter = require("./routes/web/authRouter");
const indexRouter = require("./routes/web/indexRouter");
const articleHomeRouter = require("./routes/web/articleRouter");
const sourceHomeRouter = require("./routes/web/sourceRouter");
const guestbookHomeRouter = require("./routes/web/guestbookRouter");
const pictureRouter = require("./routes/web/pictureRouter");
const trendsHomeRouter = require("./routes/web/trendsRouter");
const communityHomeRouter = require("./routes/web/communityRouter");
const animationHomeRouter = require("./routes/web/animationRouter");
// 前台路由导入

// 导入websocket
const WebSocket = require("./websocket/app");

// 创建服务器
var app = express();

// 挂载插件获取ip
app.use(expressip().getIpInfoMiddleware);

// 跨域配置，用于前端请求获取后端图片信息
app.use(
  cors({
    origin: "http://localhost:80", // 只允许 http://localhost:3000 这个域名
  })
);

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");

app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

// 路由挂载区域
// 前台认证接口（伪登录）
app.use("/api/web/auth", authHomeRouter);

// 公开接口 - 不需要用户名验证
app.use("/api/web/public/community", communityHomeRouter);

// 前台接口 - 支持用户名参数
app.use("/api/web/:username/index", userAuth, indexRouter);
app.use("/api/web/:username/article", userAuth, articleHomeRouter);
app.use("/api/web/:username/source", userAuth, sourceHomeRouter);
app.use("/api/web/:username/guestbook", userAuth, guestbookHomeRouter);
app.use("/api/web/:username/picture", userAuth, pictureRouter);
app.use("/api/web/:username/trends", userAuth, trendsHomeRouter);
app.use("/api/web/:username/animation", userAuth, animationHomeRouter);
app.use("/api/web/:username/community", userAuth, communityHomeRouter);
// token校验
app.use((req, res, next) => {
  // 判断是否是后台管理相关的接口
  if (req.url.startsWith("/api/admin")) {
    // 登录请求不需要token
    if (req.url === "/api/admin/user/login" && req.method === "POST") {
      next();
      return;
    }
    // 其他后台管理接口需要token
    const token = req.headers["authorization"]?.split(" ")[1];
    if (token) {
      // jwt校验
      JWT.verify(token, (err, data) => {
        if (err) {
          res.status(401).send({
            code: 401,
            msg: "token失效",
          });
        } else {
          // 将用户信息挂载到 req 对象
          req.adminUser = {
            id: data.id,
            username: data.username,
            role: data.role || 'user' // 用户角色
          };
          // 生成新token
          const newToken = JWT.generate(
            {
              id: data.id,
              username: data.username,
              role: data.role || 'user',
            },
            "48h"
          );
          res.setHeader("token", newToken);
          // 继续向下执行
          next();
        }
      });
    } else {
      res.status(401).send({
        code: 401,
        msg: "token不存在",
      });
    }
  } else {
    // 其他接口(前台)不需要token
    next();
  }
});

// 后台接口
app.use("/api/admin/user", userRouter);
app.use("/api/admin/article", articleRouter);
app.use("/api/admin/source", sourceRouter);
app.use("/api/admin/tag", tagsRouter);
app.use("/api/admin/category", categoryRouter);
app.use("/api/admin/guestbook", guestbookRouter);
app.use("/api/admin/imageCategory", imageCategory);
app.use("/api/admin/image", imageRouter);
app.use("/api/admin/dashboard", dashboardRouter);
app.use("/api/admin/animation", animationRouter);
app.use("/api/admin/trends", trendsRouter);
// 路由挂载区域

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

module.exports = app;
